<template>
  <div class="app-container">
    <el-form class="lookForm" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item label="班级" prop="deptId">
        <el-cascader v-model="class_cas" ref="cas" style="width: 500px;" :options="cascaderData"
          :props="{ checkStrictly: false }" @change="handleChange" clearable filterable></el-cascader>
      </el-form-item>
      <el-form-item label="学年" prop="stuYearId">
        <el-select v-model="queryParams.stuYearId" placeholder="请选择学年" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="(v, i) in stu_year_list" :key="i" :label="v.stuYearName" :value="v.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:iam:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="iamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" width="180" />
      <el-table-column label="学号" align="center" prop="stuNo" width="140" />
      <el-table-column label="班级" align="center" prop="className" width="240" />
      <el-table-column label="学年" align="center" prop="stuYearName" width="240" />
      <el-table-column label="分数" align="center" prop="score" width="140" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.srs_stu_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-folder" @click="detailVClick(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-folder" @click="lookVClick(scope.row)">查看异常的加分记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog width="900px" title="明细加分记录，如果有iam_id重复的记录请删除一条" :visible.sync="lookV">
      <el-table :data="error_list">
        <el-table-column label="学号" align="center" prop="stu_no" width="140" />
        <el-table-column label="学年" align="center" prop="stu_year_name" width="140" />
        <el-table-column label="iam_id" align="center" prop="iam_id" width="140" />
        <el-table-column label="加分项" align="center" prop="rule_name" width="140" />
        <el-table-column label="分数" align="center" prop="record_score" width="140" />
        <el-table-column label="附件" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <image-preview :src="scope.row.material" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-close" @click="deleteError(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { getStuByClass, getIam, delIam, addIam, updateIam, listSumScore, fdyAdd, listErrorAddRecord, deleteError } from "@/api/stuCQS/info-fill/iam";
import { treeStudent } from "@/api/stuCQS/basedata/student";
import { listAllYear as listYear } from "@/api/stuCQS/basedata/year";
import { listIamChild } from "@/api/stuCQS/basedata/cphRules";
import { isEmpty, fullLoading } from "@/api/helpFunc";
import store from "@/store";
import { listOwnClass, listOwnStuByClass } from "@/api/stuCQS/info-fill/stu_eva_task";



export default {
  name: "iamIndex",
  dicts: ["audius_detail_type", "srs_stu_status"],
  data() {
    return {
      class_cas: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 思想品德表格数据
      iamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitter: null,
        toAdd: null,
        material: null,
        description: null,
        auditStatus: null,
        stuYearId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "删除标记不能为空", trigger: "blur" }
        ],
      },

      //学生列表
      stu_list: [],

      //班级列表
      class_list: [],
      //学年列表
      stu_year_list: [],
      //选择的学生
      toAdd: null,
      //选择的加分项
      childType: null,
      //加分项列表
      child_list: [],
      //加分分值
      add_record: 0,
      //详情页
      detailV: false,
      //附件
      material_list: [],

      cascaderData: null,

      fdyV: false,
      isFdy: false,
      own_class: [],
      own_stu: [],
      selectedClass: null,
      selectedStu: null,
      fdyForm: {},

      lookV: false,
      error_list: [],
      errorQuery: {
        stuNo: null,
        stuYearId: null
      }
    };
  },
  watch: {
    "childType"(newVal, oldVal) {
      this.child_list.map((v) => {
        if (v.ruleId == newVal) {
          this.add_record = v.maxScore
        }
      });
    }
  },
  created() {
    //this.getList();
    this.getStuTree();
    this.getStuYear();
    this.listIamChild();
    this.getCascaderData();
    let temp = store.getters.roles;
    temp.map(x => {
      if (x == "testteacher") {
        this.isFdy = true;
        this.listOwnClass();
      }

    });

  },
  methods: {
    async deleteError(row) {
      let id = row.id;
      let loading = fullLoading(this);
      let res = await deleteError(id);
      loading.close();
      if(res.code == 200){
        this.$message.success(res.msg);
        this.listErrorAddRecord();
        this.getList();
      }
    },
    async listErrorAddRecord() {
      let loading = fullLoading(this);
      let res = await listErrorAddRecord(this.errorQuery);
      loading.close();
      if (res.code == 200) {
        this.error_list = [...res.data];
      }
    },
    async lookVClick(row) {
      this.error_list = [];
      this.errorQuery = {
        stuNo: null,
        stuYearId: null
      };
      this.errorQuery.stuNo = row.stuNo;
      this.errorQuery.stuYearId = row.stuYearId;
      await this.listErrorAddRecord();
      this.lookV = true;
    },
    async listOwnClass() {
      let res = await listOwnClass();
      if (res.code == 200) {
        this.own_class = [...res.data];
      }
    },
    async getClassStu() {
      let class_id = this.selectedClass;
      if (class_id != null) {
        let res = await listOwnStuByClass(class_id);
        this.own_stu = [...res.data];
      }
    },
    async fdyAdd() {
      let sdata = { ...this.fdyForm };
      if (this.selectedStu == null) {
        this.$message.info("请选择学生");
        return;
      }
      if (this.childType == null) {
        this.$message.info("请选择项目");
        return;
      }
      if (isEmpty(sdata.stuYearId)) {
        this.$message.info("请选择学年");
        return;
      }

      sdata.stuNo = this.selectedStu;
      sdata.ruleId = this.childType;
      let res = await fdyAdd(sdata);
      if (res.code == 200) {
        this.$message.success(res.msg);
        this.getList();
      }
    },

    // 级联选择数据
    async getCascaderData() {
      const res = await treeStudent()
      this.cascaderData = res.data
      this.cascaderData.forEach(dept => {
        dept.children.forEach(major => {
          major.children.forEach(c => {
            delete c.children
          })
        })
      });
    },
    // 级联选择的项
    handleChange(value) {
      this.queryParams = {
        ...this.queryParams,
        classId: value[2],
      }
    },
    async changeClass(val) {
      let class_id = val[val.length - 1];
      let res = await getStuByClass(class_id);
      this.toAdd = null;
      this.stu_list = res.data;
    },
    getImg(src) {
      return process.env.VUE_APP_BASE_API + src
    },

    //点击详情
    detailVClick(val) {
      console.log(val)
      this.$store.iamStuScore = val;
      this.$tab.openPage("思想品德明细", "/stuCQS/infofill/three/iamDetailList");
      //const obj = { path: "/stuCQS/infofill/three/iam_detail_list", name: "" };
      //this.$tab.refreshPage(obj);
      //this.$router.push({path:"/stuCQS/infofill/three/iam_detail_list",query:{"stuNo":val.stuNo,"stuYearId":val.stuYearId}});

    },

    //获取审核状态
    getProcessState(state) {
      let res = "";
      let dicts = this.dict.type.audius_detail_type;
      dicts.map(x => {
        if (x.value == state) {
          res = x.label;
        }
      });
      return res;
    },

    async listIamChild() {
      let res = await listIamChild();
      this.child_list = [...res.data];
    },

    //树形学生信息
    async getStuTree() {
      let res = await treeStudent();
      let data = res.data;
      this.class_list = [...data];
    },

    //列出学年信息
    async getStuYear() {
      let res = await listYear();
      this.stu_year_list = [...res.data];
    },

    /** 查询思想品德列表 */
    getList() {
      this.loading = true;
      listSumScore(this.queryParams).then(response => {
        this.iamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        submitter: null,
        toAdd: null,
        material: null,
        description: null,
        auditStatus: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        stuYearId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      let cas = this.$refs.cas;
      cas.inputValue = "";
      this.class_cas = [];
      this.queryParams.classId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加思想品德";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getIam(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改思想品德";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let sdata = {
              stuYearId: this.form.stuYearId,
              toAdd: this.toAdd,
              material: this.form.material,
              description: this.form.description,
              ruleId: this.childType,
            }
            addIam(sdata).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除思想品德编号为"' + ids + '"的数据项？').then(function () {
        return delIam(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/iam/export', {
        ...this.queryParams
      }, `iam_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.lookForm {
  .el-form-item {
    margin-bottom: 5px;
  }
}
</style>